package com.apobates.forum.toro.template.strategy;

import com.apobates.forum.toro.template.TemplateStatements;
import com.apobates.forum.toro.utils.BeanHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/**
 *
 * @param <E> 目标对象类型
 * @param <T> 起始对象类型
 */
public class TemplateSerialBasisStrategy<E,T> extends AbstractTemplateStrategy implements TemplateBasisStrategy<E,T>{
    private final static Logger logger = LoggerFactory.getLogger(TemplateSerialBasisStrategy.class);
    @Override
    public Optional<E> apply(Class<E> targetObjClass, T selectObj, List<TemplateStatements> statements, Map<String, Function<String, ?>> queries) {
        if(null == targetObjClass || null == selectObj) {
            return Optional.empty();
        }
        E targetObj = BeanHelper.buildProxyInstance(targetObjClass, selectObj);
        statements.stream().forEach(ts->{
            // ts.names Member下的属性映射key
            // ts.arguments Member下的属性表达式
            // 获取设置Orders中Member相关属性
            Map<String,Object> attrValMap = getGroupObjAttrVal(
                    BeanHelper.getAttrVal(selectObj, ts.getJoinAttr()),
                    queries.get(ts.getNames()),
                    ts.getArguments());
            // 5)批量设置Member下的相关属性
            try {
                BeanHelper.setMultiAttrVal(targetObj, attrValMap);
            }catch (Exception e){
                logger.debug(String.format(
                        "[Template][Basis]设置%s的%s属性失败. 汲及属集数量",
                        targetObj.getClass().getSimpleName(),
                        ts.getNames(),
                        attrValMap.size()));
            }
        });
        return Optional.ofNullable(targetObj);
    }

    @Override
    protected String getSentinel() {
        return "Basis";
    }
}
